package com.yzycoc.hamster.demo.common;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.sql.SqlExecutor;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * hamster-demo
 * @author Administrator
 * @since 2025/5/20 21:19
 **/
public class JsonDbImporter {

    /**
     * 自动使用默认数据源导入 JSON 数据
     */
    public static void insertFromJson(String jsonPath) {
        insertFromJson(jsonPath, null);
    }

    /**
     * 从 JSON 文件中读取数据并插入数据库
     * @param jsonPath 资源路径，如 static/20250520/threat_point.json
     * @param dataSource 可选数据源，如果为 null 则使用默认 Db.use()
     */
    public static void insertFromJson(String jsonPath, DataSource dataSource) {
        try {
            // 读取 JSON 文件
            ClassPathResource resource = new ClassPathResource(jsonPath);
            String jsonStr = resource.readStr(StandardCharsets.UTF_8);

            JSONObject root = JSON.parseObject(jsonStr);
            if (root == null || root.isEmpty()) {
                System.out.println("⚠️ JSON 文件为空：" + jsonPath);
                return;
            }

            String tableName = root.keySet().iterator().next();
            JSONArray dataArray = root.getJSONArray(tableName);
            if (dataArray == null || dataArray.isEmpty()) {
                System.out.println("⚠️ 表 [" + tableName + "] 无数据");
                return;
            }

            // 字段
            JSONObject first = dataArray.getJSONObject(0);
            List<String> fields = new ArrayList<>(first.keySet());
            String fieldPart = StrUtil.join(",", fields);
            String placeholders = StrUtil.repeatAndJoin("?", fields.size(), ",");
            String sql = StrUtil.format("INSERT INTO {} ({}) VALUES ({})", tableName, fieldPart, placeholders);

            // 使用 Db
            Db db = (dataSource != null) ? Db.use(dataSource) : Db.use();

            int success = 0;
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject row = dataArray.getJSONObject(i);
                List<Object> values = new ArrayList<>();
                for (String field : fields) {
                    values.add(row.get(field));
                }

                try {
                    System.out.println(sql);
                    SqlExecutor.execute(db.getConnection(), sql, values.toArray());
                    success++;
                } catch (Exception e) {
                    System.err.println("插入失败（跳过）：ID=" + row.get("id") + "，原因：" + e.getMessage());
                }
            }

            System.out.println("✅ 表 [" + tableName + "] 插入完成，共插入成功 " + success + " 条记录");

        } catch (Exception e) {
            System.err.println("❌ 插入出错：" + e.getMessage());
            e.printStackTrace();
        }
    }
}